package edu.intprog.egreeting;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import edu.intprog.egreeting.basic.EgreetingBaseServlet;
import edu.intprog.egreeting.beans.Messages;

/**
 * Servlet implementation class for Servlet: GreetingSelectorServlet
 *
 */
public class GreetingSelectorServlet extends EgreetingBaseServlet implements javax.servlet.Servlet {
	static final long serialVersionUID = 1L;

	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public GreetingSelectorServlet() {
		super();
	}   	 	

	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if( request.getSession().getAttribute("user")==null)
		{
			//simple security measure
			getServletContext().getRequestDispatcher("/StartServlet").forward(request, response);
			return;
		}
		
		Properties titles = new Properties();

		//get the template titles
		String errMsg = getTitlesFromDB(titles);

		if (errMsg.length()>0) 
		{
			//error was found - report it
			Messages msgDef = new Messages();
			msgDef.set_errorMessage(errMsg + "<br/>");
			request.setAttribute("msgs", msgDef);
			getServletContext().getRequestDispatcher("/messages.jsp").forward(request, response);
			return;
		}
		request.setAttribute("titles", titles);
		getServletContext().getRequestDispatcher("/templateSelector.jsp").include(request, response);
	} 

	/**
	 * getTitlesFromDB
	 * 
	 * run a JDBC query that returns the template titles - the results will be appended
	 * to the given properties where the title name is both the key and value
	 * 
	 * @param results - a properties to be filled with the result titles
	 * @return error string
	 */
	private static synchronized String getTitlesFromDB(Properties results)
	{
		String errMsg = new String();
		Connection conn = null;
		String userName = "egreeting";
		String password = "burgul";
		String schemeName = "egreeting";
		String url = "jdbc:mysql://localhost/" + schemeName + "?user="
		+ userName
		+ "&password="
		+ password;

		try {
			Class.forName ("com.mysql.jdbc.Driver").newInstance ();
			conn = DriverManager.getConnection (url);
			Statement s = conn.createStatement ();
			s.executeQuery ("SELECT TITLE FROM GREETING_TEMPLATES");
			ResultSet rs = s.getResultSet ();
			while (rs.next ())
			{
				String title = rs.getString ("TITLE");
				results.put(title,title);
			}
			rs.close ();
			s.close ();
		} catch (Exception e) {
			errMsg = e.getMessage();
		}
		finally {
			if (conn != null)
			{
				try
				{
					conn.close ();
				}
				catch (Exception e) { /* ignore close errors */ }
			}
		}

		return errMsg;
	}
}